﻿package Code{
	
	import flash.display.Sprite;
	import flash.geom.Rectangle;
	
	public class Ball extends Sprite {
		public var center:Vertex;								//center of the ball
		public var vx:Number = 0;   							//velocity in X direction
		public var vy:Number = 0;								//velocity in Y direction
		public var radius:Number;								//ball's radius
		private var color:uint;									//color of ball
		public var bounce:Number = -1.0;						//bounce is the constant used to change velocity when the ball collides
		
		//constructor
		public function Ball(center:Vertex, radius:Number, color:uint= 0x880088) {
			this.center = center;
			this.radius = radius;
			this.color = color;
			this.x=0;
			this.y=0;
			init();
		}
		
		//initialize
		public function init():void {
			graphics.clear();
			graphics.beginFill(color);
			graphics.drawCircle(center.x, center.y, radius);
			graphics.endFill();
		}
		
		//check to see if the ball is off the stage, and bounces it back in
		public function checkWalls():void {
			
			if(center.x + radius > stage.stageWidth) {
				center.x = stage.stageWidth - radius;
				vx *= bounce;
			}
			else if(center.x - radius < 0) {
				center.x = radius;
				vx *= bounce;
			}
			if(center.y + radius > stage.stageHeight) {
				center.y = stage.stageHeight - radius;
				vy *= bounce;
			}
			else if(center.y - radius < 0) {
				center.y = radius;
				vy *= bounce;
			}
			
		}
		
		public function checkLines(line:Bar):void {
			
			//var bounds:Rectangle = line.getBounds(this);
			if(hitTestObject(line))
			{
			// commonly used variables
			var cos:Number = Math.cos(line.getAngleAB());
			var sin:Number = Math.sin(line.getAngleAB());
			
			// get position of ball relative to line
			var x1:Number = center.x - line.b.x;
			var y1:Number = center.y - line.b.y;
			
			// rotate coordinates
			var x2:Number = cos * x1 + sin * y1;
			var y2:Number = cos * y1 - sin * x1;
			
			// rotate velocity
			var vx1:Number = cos * vx + sin * vy;
			var vy1:Number = cos * vy - sin * vx;
			
			
			// perform bounce with rotated values
			if(y2 > -height / 2)
			{
				y2 = height / 2;
				vy1 *= bounce;
			}
			
			// rotate everything back
			x1 = cos * x2 - sin * y2;
			y1 = cos * y2 + sin * x2;
			vx = cos * vx1 - sin * vy1;
			vy = cos * vy1 + sin * vx1;
			
			// restore ball position
			center.x = line.b.x + x1;
			center.y = line.b.y + y1;		
			
			line.b.vy -= (vy/5);
			}
		}
	}
}